import { ElLoading } from 'element-plus'

let loadingCount = 0
let loadingInstance

const startLoading = (loadingText) => {
  if (!loadingText) {
    loadingText = '加载中,请稍等……'
  }
  loadingInstance = ElLoading.service({
    fullscreen: true,
    lock: true,
    text: loadingText,
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

const endLoading = () => {
  loadingInstance.close()
}

const loading = {
  show: (loadingText) => {
    if (loadingCount === 0) {
      startLoading(loadingText)
    }
    loadingCount += 1
  },
  hide: () => {
    if (loadingCount <= 0) {
      return
    }
    loadingCount -= 1
    if (loadingCount === 0) {
      endLoading()
    }
  },
}

export default loading
